package com.icecloud.cloud.upms.conf.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.icecloud.cloud.upms.common.utils.RestfulResponseBody;

/**
 * 登录验证成功
 * @author penghaozhong
 *
 */
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	
	
	public RestAuthenticationSuccessHandler() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		
		RestfulResponseBody body = new RestfulResponseBody();
		body.setReason("登陆成功");
		body.setResultFlag(1);
		
		PrintWriter writer;  
        response.setStatus(200);  
        writer = response.getWriter();  
        writer.write(new ObjectMapper().writeValueAsString(body));  
        writer.flush();  
        writer.close();
		
		clearAuthenticationAttributes(request);

	}
	
	protected final void clearAuthenticationAttributes(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return;
		}
		session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
	}

}
